package com.etms.service;

import com.etms.mapper.AccountsMapper;
import com.etms.mapper.AttendAdminMapper;
import com.etms.pojo.AccountAdmin;
import com.etms.pojo.Accounts;
import com.etms.utils.DateUtils;
import com.etms.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class AdcService {
    @Autowired
    AttendAdminMapper attendAdminMapper;
    @Autowired
    AccountsService accountsService;
    @Autowired
    ThreadService threadService;
    public Result getList() {
        List<AccountAdmin>accountAdmins=attendAdminMapper.findAll();
        return Result.successed(accountAdmins);
    }

    public Result updatePrice(AccountAdmin accountAdmin) {
        Integer id = accountAdmin.getId();
        AccountAdmin adc=attendAdminMapper.findById(id);
        //判断是入还是出
        Integer addOrSub = adc.getAddOrSub();
        Double owePrice = adc.getOwePrice();//应收应付
        Double factToUpdate = accountAdmin.getFactToUpdate();//要收多少钱
        Accounts accounts=accountsService.findById(adc.getAcid());
        Double premoney=accounts.getPrice();//账户原先的钱
        String datetime= DateUtils.getDateTime(new Date());
        //1+ 2-
        if (addOrSub==1){//出库 赚钱 账户加钱
            if(factToUpdate>owePrice){
                return Result.failed("你收多了！！请重新输入");
            }
            adc.setOwePrice(owePrice -factToUpdate);//更新数额
            if (adc.getOwePrice()<=0){
                adc.setIsok(true);//表示结清
            }
            accountsService.updateMoney(premoney,premoney+factToUpdate,adc.getAcid());//加钱
            String msg = adc.getMsg();
            String types = msg.split("->")[0];
            BigDecimal d1 = new BigDecimal(Double.toString(factToUpdate));
            types+="账户收费"+d1+"元";//记录信息
            threadService.insertMsg(accountsService,types);
        }
        else {//入库 花钱
            if(factToUpdate>owePrice){
                return Result.failed("你付多了！！请重新输入");
            }
            adc.setOwePrice(owePrice-factToUpdate);
            if (adc.getOwePrice()<=0){
                adc.setIsok(true);//表示结清
            }
            accountsService.updateMoney(premoney,premoney-factToUpdate,adc.getAcid());//付钱
            String msg = adc.getMsg();
            String types = msg.split("->")[0];
            BigDecimal d1 = new BigDecimal(Double.toString(factToUpdate));
            types+="账户付费"+d1+"元";//记录信息
            threadService.insertMsg(accountsService,types);
        }
        adc.setFactToUpdate(adc.getFactToUpdate()+factToUpdate);
        attendAdminMapper.updateADC(adc);//更新adc
        return Result.successed(null);
    }
}
